package com.briup.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.briup.reggie.common.CustomException;
import com.briup.reggie.dto.DishDto;
import com.briup.reggie.dto.SetmealDto;
import com.briup.reggie.entity.*;
import com.briup.reggie.mapper.SetmealMapper;
import com.briup.reggie.service.CategoryService;
import com.briup.reggie.service.DishService;
import com.briup.reggie.service.SetmealDishService;
import com.briup.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;
    /**
     * 新增具体套餐,保存菜品和套餐的关联关系
     * @param setmealDto
     */
    @Override
    @Transactional
    @CacheEvict(value = "setmealCache",allEntries = true)
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐基本信息,操作setmeal，执行insert操作
        this.save(setmealDto);
        //保存菜品和套餐关联关系,操作setmeal_dish，执行insert操作
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //setmealDishes中套餐id因为套餐还未创建，还未生成id，需要添加进去
        setmealDishes.stream().map((item)->{
            //等套餐创建完毕后会自动赋上id，这时候调用就行
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 套餐分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public Page<SetmealDto> page(int page, int pageSize, String name) {
        //分页构造器
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        Page<SetmealDto> dtoPage = new Page<>();

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件
        queryWrapper.like(name!=null,Setmeal::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        //执行查询
        Page<Setmeal> setmealPage = this.page(pageInfo, queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");

        //为了给列表添加一个菜品分类数据
        //1.获取菜品（Dish）列表
        List<Setmeal> records = pageInfo.getRecords();
        //2.遍历，给每个数据加上菜品分类名称
        List<SetmealDto> list = records.stream().map((item)->{
            //拷贝菜品基础属性
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item,setmealDto);

            //分类id
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category!=null) {
                String categoryName = category.getName();
                //将菜品分类名称赋值给dishDto列表
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());

        //设置页面列表，这里面就含有了菜品分类名称属性
        dtoPage.setRecords(list);

        return dtoPage;
    }

    /**
     * 根据id查询套餐，及其包含的菜品信息
     * 回显
     * @param id
     * @return
     */
    @Override
    public SetmealDto getByIdWithSetmeal(Long id) {
        //查询套餐基本信息，从dish中查
        Setmeal setmeal = this.getById(id);

        //把setmeal基本信息拷贝到setmealDto中
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal,setmealDto);

        //查询套餐对应的菜品
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.eq(SetmealDish::getSetmealId,id);
        //执行查询
        List<SetmealDish> setmealDishes = setmealDishService.list(queryWrapper);

        //最后单独添加上对应的菜品信息
        setmealDto.setSetmealDishes(setmealDishes);

        return setmealDto;
    }

    /**
     * 修改菜品信息
     * @param setmealDto
     */
    @Override
    @CacheEvict(value = "setmealCache",allEntries = true)
    public void updateWithSetmeal(SetmealDto setmealDto) {
        //更新setmeal表基本信息
        this.updateById(setmealDto);
        //清理当前套餐对应菜品表的delete操作
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,setmealDto.getId());
        setmealDishService.remove(queryWrapper);
        //重新添加当前套餐包含菜品的数据
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //setmealDishes中套餐id因为套餐还未创建，还未生成id，需要添加进去
        setmealDishes.stream().map((item)->{
            //等套餐创建完毕后会自动赋上id，这时候调用就行
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 起售与停售
     * @param status
     * @param ids
     */
    @Override
    @CacheEvict(value = "setmealCache",allEntries = true)
    public void setStatus(Integer status, List<Long> ids) {
        Setmeal setmeal = new Setmeal();
        for (Long setmealId : ids) {
            setmeal.setId(setmealId);
            setmeal.setStatus(status);
            this.updateById(setmeal);
        }
    }

    /**
     * 删除套餐，同时删除套餐关联的菜品数据
     * @param ids
     */
    @Override
    @Transactional
    @CacheEvict(value = "setmealCache",allEntries = true)
    public void removeWiteDish(List<Long> ids) {
        //select count(*) from Setmeal where id in(1,2,3...) and where status = 1
        //查询套餐状态，判断是否可以删除
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);
        int count = this.count(queryWrapper);

        //判断
        if (count>0){
            throw new CustomException("套餐正在售卖，不能删除");
        }

        //如果可以删除,先删除套餐基本信息
        this.removeByIds(ids);

        //在删除setmeal_dish表中关联菜品数据
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);

        setmealDishService.remove(lambdaQueryWrapper);

    }

    /**
     *  根据条件查询套餐数据
     * @param setmeal
     * @return
     */
    @Override
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId+'_'+#setmeal.status",condition = "#setmeal.categoryId!=null")
    public List<Setmeal> list(Setmeal setmeal) {
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus()!=null,Setmeal::getStatus,setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = this.list(queryWrapper);
        return list;
    }
}
